// 美团优选数据采集
// 美团版本 12.11.403
let template = []
let save_excel = null
let run_state = false
let city_config = {}
let category_list = []
let mt_city_list = []
let save_path = ""


function click_bounds(ui_object) {
    automator.click(ui_object.bounds().centerX(), ui_object.bounds().centerY())
    sleep(200)
}

// api接口获取城市对照数据
function get_city_for_api() {
    let city_res = http.get("https://www.mxnzp.com/api/address/list?app_id=&app_secret=").body.json()
    //解析body
    if (city_res['code'] == 1) {
        for (let i = 0; i < city_res['data'].length; i++) {
            let city_info = city_res['data'][i]
            if (city_info['pchilds'][0]['name'] == '市辖区') {
                city_config[city_info['name']] = city_info['name']
            } else {
                let city_child = city_info["pchilds"]
                for (let x = 0; x < city_child.length; x++) {
                    city_config[city_child[x]["name"]] = city_info["name"]
                }
            }
        }
    } else {
        console.error("获取市-省信息失败!")
    }
}


// 存储数据初始化
function init_data() {
    save_path = "/storage/emulated/0//rpa/result/美团优选数据采集" + time.date() + ".xls"
    if (files.exists(save_path)) {
        files.remove(save_path)
    }
}


function open_save_excel(city_name) {
    console.log(save_path)
    save_excel = excel.open(save_path, city_name)
    excel.appendRow(save_excel, ["产品", "售价", "销量"])
    excel.syncDisk(save_excel)
}


// 初始化类目点击 
function init_category_() {
    sleep(1500)
    console.hide()
    let all_finds = selector().text("全部").find()
    for (let i = 0; i < all_finds.length; i++) {
        try {
            if (all_finds[i].parent().id().indexOf("sub-category-item") != -1) {
                click_bounds(all_finds[i].parent().next())
            }
        } catch (e) {
            continue
        }
    }
    console.show()
    sleep(1500)
}


function go_next_category() {
    while (true) {
        if (selector().id("category-Landing-wrapper").findOne(200).child(3).child(1).child(0).child(0).text() == "全部") {
            break
        } else {
            automator.swipeDown()
            sleep(1000)
        }
    }
}


//类目数据获取开始
function get_category_data(city_name) {
    open_save_excel(city_name)
    init_category_()
    template = []
    while (true) { // 循环获取开始
        let category_views = selector().id("category-Landing-wrapper").findOne(200).child(3).child(1).child(1).child(1).child(0)
        if (selector().id("category-Landing-wrapper").findOne(200).child(3).child(1).child(0).child(0).text() == "全部") {
            init_category_()
        }
        //type_level1 = category_list[category_index]
        for (let i = 1; i < 10; i++) {
            try {
                let category_item = category_views.child(i)
                //let category_type = selector().id("category-Landing-wrapper").findOne(200).child(3).child(1).child(0).child(0).text()
                let name = category_item.child(0).child(1).text() // 名称+规格
                if (name.length == 0) {
                    name = category_item.child(0).child(1).child(1).text()
                }
                let price = ""
                let price_views = category_item.find(selector().text("¥"))[0].parent().children()
                for (let x = 0; x < price_views.length; x++) {
                    price += price_views[x].text()
                }
                price = price.match(/\d+.\d+/)
                let sale_count = category_item.find(textContains("销量"))
                let sell_count = ""
                if (sale_count.length == 0) {
                    sell_count = "暂无销量"
                } else {
                    sell_count = category_item.find(textContains("销量"))[0].text().replace("销量", "") // 销量
                }
                if (template.indexOf(name) == -1) {
                    console.log("产品:" + name + ",售价:" + price + ",销量:" + sell_count)
                    excel.appendRow(save_excel, [name, price[0], sell_count])
                    excel.syncDisk(save_excel)
                    template.push(name)
                }
            } catch (ex) {
                continue
            }
        }
        if (selector().text("已经到底了").exists()) {
            break
        }
        automator.swipeDown()
        sleep(2000)

    }
}


//设备初始化
function reset_devices() {
    device.wakeUpIfNeeded()
    console.log('>>>准备初始化环境<<<')
    automator.home() // 点击home按键
    sleep(500)
    automator.recents() // 展开最近任务
    selector().id('clearAnimView').findOne().click()
    console.log('>>>环境初始化完成<<<')
}

//监控模块
function wacther() {
    console.warn(">>>启动监听<<<")
    try {
        threads.start(function () {
            while (run_state) {
                if (selector().id('red_packet_close').exists()) {
                    selector().id('red_packet_close').findOneOrStop(1000).click()
                }
                if (selector().id('change_city_close').exists()) {
                    selector().id('change_city_close').findOneOrStop(1000).click()
                }
                if (selector().id('btn_close').exists()) {
                    selector().id('btn_close').findOne(2000).click()
                }
            }
        })
    } catch (ex) {
        console.error(ex)
        stop("未知弹窗引起流程失败")
    }
}



function get_city_local() {
    console.hide()
    selector().id('city_layout').findOne(200).click() //初始化选择
    sleep(2000)
    click_bounds(selector().text('阿坝').findOne(2000))
    selector().desc("优选").findOne(200).click()
    sleep(2000)
    click_bounds(selector().id('top-banner-and-search').findOne(200).child(0).child(1))
    selector().id('mmp-div-container').waitFor(60000)
    click_bounds(selector().text("搜索更多地址或自提点").findOne(3000))
    sleep(2500)
    for (let i = 0; i < 20; i++) {
        if (!selector().id('lettleList').exists()) {
            click_bounds(selector().id("mmp-div-container").find()[0].child(0).child(1).child(0))
            sleep(2000)
        } else {
            break
        }
    }
    click_bounds(selector().id('lettleList').findOne(200).child(0))
    console.show()
    while (true) {
        let city_list = selector().id('scroll-v').findOne(200).child(0).child(10).children()
        for (let i = 0; i < city_list.length; i++) {
            let city_name = city_list[i].text()
            if (city_name == "已开通地区" || city_name.length < 2) {
                continue
            } else {
                if (mt_city_list.indexOf(city_name) == -1) {
                    mt_city_list.push(city_name)
                }
                if (city_name == "舟山") {
                    console.show()
                    automator.back()
                    sleep(200)
                    automator.back()
                    sleep(200)
                    automator.back()
                    return;
                }
            }
        }
        automator.swipeDown()
    }

}


function change_pickup_centers(city_name) {
    sleep(1000)
    console.hide()
    click_bounds(selector().id('top-banner-and-search').findOne(200).child(0).child(1))
    selector().id('mmp-div-container').waitFor(60000)
    click_bounds(selector().text("搜索更多地址或自提点").findOne(3000))
    for (let i = 0; i < 20; i++) {
        if (!selector().id('lettleList').exists()) {
            click_bounds(selector().id("mmp-div-container").find()[0].child(0).child(1).child(0))
            sleep(2000)
        } else {
            break
        }
    }
    click_bounds(selector().text("请输入城市/区县搜索").findOne(2000))
    selector().text("请输入城市/区县搜索").findOne(2000).setText(city_name)
    sleep(2000)
    click_bounds(selector().textContains(city_name).find()[0])
    click_bounds(selector().text("请输入地址或自提点名称").findOne(2000))
    selector().text("请输入地址或自提点名称").setText("自提点")
    sleep(1500)
    click_bounds(selector().text("自提点").find()[2])
    //click_bounds(selector().text("选这个").find()[0])
    selector().textContains("确认自提点").waitFor(1500)
    click_bounds(selector().textContains("确认自提点").findOne(200))
    console.show()
    console.warn("自提点选择完成!")
}


function loop_city(city_name) {
    let city_key = Object.keys(city_config)
    let city_key_filter = city_key.filter(e => eval("/" + city_name + "\S*/").test(city_name))[0]
    if (city_key_filter != undefined) {
        change_pickup_centers(city_name)
        selector().text("蔬菜豆品").waitFor(2000)
        click_bounds(selector().text("蔬菜豆品").findOne(200))
        //open_save_excel(city_name)
        get_all_category_item(city_name)
        get_category_data(city_name)
        automator.back()
    } else {
        console.log(city_name + "不存在!")
    }
}


function change_city(city_name) {
    selector().id('city_layout').findOne(1000).click()
    selector().id("search_edit").findOne(1000).setText(city_name)
    selector().id("suggest_city_list_view").findOne(1000).child(1).click()
    if (selector().id('change_city_close').exists(200)) {
        selector().id('change_city_close').findOneOrStop(1000).click()
    }
}


function run_() {
    run_state = true
    reset_devices() // 初始化
    init_data()
    wacther() // 启动监控
    app.launchAppVersionOrStop("美团", '12.11.403') // 打开美团
    //get_city_for_api()
    //get_city_local() // 获取美团的城市id
    for (let i = 0; i < mt_city_list.length; i++) {
        loop_city(mt_city_list[i])
    }
    run_state = false
}

// 入口
console.show()
console.clear()
console.log(">>>开始执行美团优选采集流程<<<")
run_()